package com.project.petLossSystem.task;

import com.project.petLossSystem.common.Constants;
import com.project.petLossSystem.mapper.PetPostMapper;
import com.project.petLossSystem.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Component
@EnableScheduling // 定时任务
public class viewsTask {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private PetPostMapper petPostMapper;

    /**
     * 每30s刷新浏览量
     */
    @Scheduled(cron = "0/30 * * * * *")
    public void updateViews() {
        // 获取当前的浏览量表
        Map<String, String> viewsMap = redisCache.hashEntries(Constants.HASH_KEY_FOR_VIEWS);
        if (CollectionUtils.isEmpty(viewsMap)) {
            return;
        }
        // 更新数据库
        if (petPostMapper.updateViews(dealMap(viewsMap)) > 0) {
            // 删除key
            redisCache.delete(Constants.HASH_KEY_FOR_VIEWS);
        }
        // 不做更改
    }

    public Map<String, Long> dealMap(Map<String, String> map) {
        Map<String, Long> newMap = new HashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            newMap.put(entry.getKey(), Long.valueOf(entry.getValue()));
        }
        return newMap;
    }

    /**
     * 每天0点删除匹配图
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void deleteMatch() {
        File match = new File(Constants.File_IMAGE_UPLOAD_DIC + Constants.MATCH_LOCAL_DIC);
        File[] images = match.listFiles();
        if (images != null) {
            for(File file: images){
                file.delete();
            }
        }
    }
}
